﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Hu01
{
	public class InputBuffer
	{
		byte[] buffer;
		int offset;
		uint bitBuffer;
		int validBits;

		public InputBuffer(byte[] buffer)
		{
			this.buffer = buffer;
			this.offset = 0;
			this.bitBuffer = (uint)((uint)ReadUInt16() << 16) | ReadUInt16();
			this.validBits = 16;
		}

		public ushort PeekBits(int count)
		{
			return count == 0 ? (ushort)0 : (ushort)(bitBuffer >> (32 - count));
		}

		public void SkipBits(int count)
		{
			bitBuffer <<= count;
			validBits -= count;
			if (validBits < 0)
			{
				bitBuffer |= (uint)ReadUInt16() << (-validBits);
				validBits += 16;
			}
		}

		public ushort ReadUInt16()
		{
			if (offset < buffer.Length - 1)
				return (ushort)(buffer[offset++] | (buffer[offset++] << 8));
			return ReadByte();
		}

		public byte ReadByte()
		{
			if (offset < buffer.Length)
				return buffer[offset++];
			return 0;
		}
	}
}
